package com.example.safehome;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.tablemanager.Connector;

import java.util.Date;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class FireSensorActivity extends AppCompatActivity implements View.OnClickListener {

    //音频播放器声明
    private MediaPlayer mediaPlayer=new MediaPlayer();

    //控件声明
    TextView textViewSystemStatus ;
    TextView textViewFirePosition ;
    TextView textViewIsFire;
    TextView textViewIsRunning ;
    Button buttonDetect;
    Button buttonQuit;
    Button buttonTest;
    Button buttonRecord;
    Button button119;
    FireSensor fireSensor = new FireSensor();

    //是否正在检测
    boolean isdetect=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.fire_activity_main);
        textViewSystemStatus = (TextView) findViewById(R.id.tv_system_status);
        textViewFirePosition = (TextView) findViewById(R.id.tv_position);
        textViewIsFire = (TextView) findViewById(R.id.tv_is_fire);
        textViewIsRunning = (TextView) findViewById(R.id.tv_is_running);
        buttonDetect = (Button) findViewById(R.id.bt_detect_2);
        buttonQuit=(Button)findViewById(R.id.bt_quit_2);
        buttonTest=(Button)findViewById(R.id.bt_test_2);
        buttonRecord=(Button)findViewById(R.id.bt_record_2) ;
        button119 = (Button) findViewById(R.id.bt_119);
        buttonRecord.setOnClickListener(this);
        buttonDetect.setOnClickListener(this);
        buttonQuit.setOnClickListener(this);
        buttonTest.setOnClickListener(this);
        button119.setOnClickListener(this);

        mediaPlayer=MediaPlayer.create(this,R.raw.warning);
        mediaPlayer.setLooping(true);
        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        SQLiteDatabase WarningRecardDataBase = Connector.getDatabase();

        //写数据库
        textViewFirePosition.addTextChangedListener(new TextWatcher() {

            // charSequence为在你按键之前显示的字符串  start为新字符串与charSequence开始出现差异的下标
            // count表示原字符串的count个字符  after表示将会被after个字符替换
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            }

            // 按键之前字符串的start位置的before个字符已经被count个字符替换形成新字符串charSequence
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            // afterTextChanged中 editable为EditText显示的内容
            //写入数据库
            @Override
            public void afterTextChanged(Editable editable) {
                FireWarningRecord record=new FireWarningRecord();
                record.setFireTime(new Date(java.lang.System.currentTimeMillis()));
                record.setFirePlace(fireSensor.getFirePosition());
                record.setIsCallPolice(false);
                record.setDetail("");
                record.saveThrows();
            }
        });

        //音频权限获取
        if (ContextCompat.checkSelfPermission(FireSensorActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(FireSensorActivity.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        // 返回
        Button btnBack = (Button) findViewById(R.id.bt_fire_back);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fireSensor.quit();
                mediaPlayer.pause();
                finish();
            }
        });
    }

    //权限获取
    public void onRequestPermissionResult(int requestCode,String[] permissions,int[] grantResults){
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                  break;
                }
                else{
                    Toast.makeText(this,"拒绝权限将无法访问程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    //按钮逻辑
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_detect_2 :
                fireSensor.detect();
                isdetect=true;
                String Status, breakInPosition, isBreakIn, isRunning;
                if (fireSensor.getStatus()) {
                    Status = "正常";
                    if (fireSensor.isOnFire()) {

                        textViewIsFire.setText("房屋发生火灾");
                        textViewFirePosition.setText(fireSensor.getFirePosition());

                        mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                    }
                    else {
                        textViewIsFire.setText("房屋未发生火灾");
                    }
                }
                else
                    Status = "异常";
                textViewSystemStatus.setText(Status);
                textViewIsRunning.setText("系统运行中...");
                break;
            case R.id.bt_quit_2 :
                fireSensor.quit();
                isdetect=false;
                textViewIsRunning.setText("系统未运行");
                mediaPlayer.pause();
                textViewIsFire.setText("");
                textViewFirePosition.setText("");
                break;
            case R.id.bt_record_2:
                Intent intent=new Intent(FireSensorActivity.this, FireRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_test_2:
                fireSensor.test();
                if(isdetect==true)
                {
                    if (fireSensor.getStatus()) {
                        Status = "正常";
                        if (fireSensor.isOnFire()) {
                            textViewIsFire.setText("房屋发生火灾");
                            textViewFirePosition.setText(fireSensor.getFirePosition());
                            mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                        }
                        else {
                            textViewIsFire.setText("房屋未发生火灾");
                        }
                    }
                    else
                        Status = "异常";
                }
                break;

            case R.id.bt_119:
                Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + 119));
                startActivity(intent_call);

            default:
                break;
            }
    }
}
